// 和用户相关的状态管理

import { createSlice } from "@reduxjs/toolkit";
import { http } from '@/utils/index';
import {login,getUseInfo} from '@/apis/user'
import {setToken as _setToken,getToken,removeToken} from '@/utils'
const userStore = createSlice({
    name: 'user',
    // 数据状态
    initialState: {
        token: getToken('user_token') || '',
        userInfo: getToken('user_info') || ''
    },
    // 同步的修改方法
    reducers: {
        setToken(state, action) {
            state.token = action.payload
             // 本地缓存
             _setToken(action.payload,'user_token')
        },
        setUserInfo(state,action) {
            state.userInfo = action.payload
            // b本地缓存
            _setToken(action.payload,'user_info')
        },
        // 清除用户信息
        clearUserInfo(state) {
            state.token = ''
            state.userInfo = {}
            removeToken('user_token')
            removeToken('user_info')
        }
    }
})
// 结构出方法
const { setToken,setUserInfo,clearUserInfo } = userStore.actions

const userReducer = userStore.reducer
// 异步登录 
let loginApi = (loginForm) => {
    console.log(123);

    return async (dispatch) => {
        let res = await login(loginForm)
        // 提交同步修改token
        dispatch(setToken(res.data.token))
    }
}
// 获取用户信息
const fetchUserInfo = () => {
    return async (dispatch) => {
      const res = await getUseInfo()
      dispatch(setUserInfo(JSON.stringify(res.data)))
    }
  }
export { setToken, loginApi,fetchUserInfo,clearUserInfo }

export default userReducer